// 云函数入口文件
const cloud = require('wx-server-sdk')
const dayjs = require('dayjs')
dayjs.extend(require('dayjs/plugin/utc'))
dayjs.extend(require('dayjs/plugin/timezone'))
dayjs.tz.setDefault('Asia/Shanghai')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async event => {
  const { sn } = event
  if (!sn) {
    throw new Error('no sn')
  }

  const now = dayjs().tz()
  const today = now.format('YYYY-MM-DD')

  const {
    data: [sData],
  } = await db.collection('screen').where({ sn }).get()
  if (!sData) {
    throw new Error('screen not found')
  }

  let { data } = await db
    .collection('video-cast')
    .where({ screenId: sData._id, date: today })
    .get()

  return [].concat(...data.map(v => v.resources.map(v => v.url)))
}
